#include <iostream>

#include "section.hpp"
#include "tool.hpp"

using namespace std;

section_t::section_t()
{
	pos = 0;
	len = 0;
}

bool section_t::open(ifstream& wadstream, uint32_t tikpos, uint32_t contentpos)
{
	if(!wadstream.is_open())
		return false;
	wadstream.seekg(tikpos);
	len = get32(wadstream);
	pos = contentpos;
	return true;
}

bool section_t::unpack(ifstream& wadstream, string path)
{
	if(!wadstream.is_open())
		return false;
	bool ret = true;
	uint8_t* buffer = NULL;
	try
	{
		buffer = new uint8_t[len];
	}
	catch(exception& e)
	{
		cerr << "Error: " << e.what() << endl;
		return false;
	}
	ofstream outfile(path, ios_base::out | ios_base::binary);
	wadstream.seekg(pos);


	wadstream.read(reinterpret_cast<char*>(buffer), len);

	outfile.write(reinterpret_cast<char*>(buffer), len);
	if(outfile.bad())
	{
		cerr << "Something happened trying to write " << path << endl;
		ret = false;
	}
	delete[] buffer;
	outfile.close();
	
	return ret;
}

